// app.js
App({

    onLaunch() {
        // 展示本地存储能力
        // const logs = wx.getStorageSync('logs') || []
        // logs.unshift(Date.now())
        // wx.setStorageSync('logs', logs)
        // wx.clearStorage()
        console.info('this.callback=' + this.callback)
        this.checkLogin(res => {
            console.info("is_login的值：" + res.is_login);
            if (!res.is_login) { //未登录过
                this.login_1128_2();
            }
        });


        // 获取头部导航信息，传递给自定义头部的页面，自适应不同机型的高度
        let that = this;
        // 胶囊信息可以通过 wx.getMenuButtonBoundingClientRect() 获取；
        this.globalData.capsule = wx.getMenuButtonBoundingClientRect() //获取胶囊宽高及位置
        // 全局缓存 
        //   wx.setStorageSync('capsule', config)
        //获取系统信息
        const windowInfo = wx.getWindowInfo()
        console.log(windowInfo.safeArea)
        console.log(windowInfo.screenTop)
        that.globalData.windowHeight = windowInfo.windowHeight;
        that.globalData.windowWidth = windowInfo.windowWidth;
        that.globalData.statusBarHeight = windowInfo.statusBarHeight;
        that.globalData.innerPaddingRight = 'padding-right:' + (windowInfo.windowWidth - this.globalData.capsule.right) + 'px';
        that.globalData.innerPaddingLeft = 'padding-left:' + (windowInfo.windowWidth - this.globalData.capsule.right) + 'px';
        that.globalData.leftWidth = 'padding-left:' + (windowInfo.windowWidth - this.globalData.capsule.left) + 'px';

        // 状态栏信息
        that.globalData.ztHeight = windowInfo.statusBarHeight;
        // 导航栏的top 是 状态栏的高度
        that.globalData.dhlTop = windowInfo.statusBarHeight;
        // dhlTop:0,
        // 导航栏的高度 = 状态栏高度 + 胶囊高度 +（胶囊top - 状态栏高度）* 2 
        that.globalData.dhlHeight = this.globalData.capsule.height + (this.globalData.capsule.top - windowInfo.statusBarHeight) * 2;
    },

    checkLogin: function (callback) { //checkLogin检查登录状态，再去执行
        var token = this.globalData.token;
        if (!token) { //token值为空，证明没有登录
            // 再去读缓存，看看是否有token
            token = wx.getStorageSync("token"); //从缓存中同步取token
            //这句代码一定要得出结果方便我们后续的判断，于是使用同步去读取
            if (token) {
                this.globalData.token = token; //将缓存里面的token放入globalData的token里面
            } else {
                callback({ is_login: false }); //未登录
                return;
            }
        }
    },

    login_1128_2: function () {
        var that = this;
        return that.loginPromise().then(code=>that.tokenPromise(code)).then(tokenRes => {
            return new Promise(function (resolve, reject) {
                const tokenResCode = tokenRes.data.code;
                if (tokenResCode == 1) {
                    // 获取用户信息成功，返回token
                    let tokenStr = tokenRes.data.data;
                    wx.setStorageSync("token", tokenStr);
                    that.globalData.token = tokenStr;
                    resolve(tokenStr);
                }
            })
        })
    },

    loginPromise:function(){
        return new Promise(function (resolve, reject) {
            wx.login({ //获取用户登录临时凭证（code）
                success: (res) => {
                    resolve(res.code);
                },
                fail: (res) => {
                    reject(new Error('获取用户登录临时登录凭证失败：' + JSON.stringify(res)));
                }
            })
        })
    },
    tokenPromise:function(codeRes){
        var _this = this;
        return new Promise(function (resolve, reject) {
            wx.request({
                url: 'http://' + _this.globalData.ipStr + '/weixin/getToken?code=' + codeRes,
                method: 'POST',
                data: {},
                header: {
                    'content-type': 'application/json;charset=UTF-8;'
                },
                success: res => { //wx.request成功的回调
                    console.log('res.data=' + JSON.stringify(res.data));
                    resolve(res)
                },
                fail: res => {
                    reject(new Error('登录失败：res=' + JSON.stringify(res)));
                }
            })
        })
    },
    customer_wx_login_register: function (ip, sessionKeyOpenid, that) {
        // 另外添加的获取用户信息开始
        // 微信授权
        wx.getUserInfo({
            success: function (res) {
                console.log('获取用户信息+' + JSON.stringify(res));
                wx.request({
                    url: 'http://' + ip + '/weixin/registerUser',
                    method: 'POST',
                    header: {
                        'content-type': 'application/json;charset=UTF-8'
                    },
                    data: {
                        "userInfo": res.userInfo,
                        'sessionKeyOpenid': sessionKeyOpenid,
                        'iv': res.iv,
                        'encryptedData': res.encryptedData
                    },
                    success: res => { //wx.request成功的回调
                        console.info('新注册用户的返回信息=' + JSON.stringify(res))
                        wx.setStorageSync("token", res.data.data.token);
                        wx.setStorageSync("userId", res.data.data.userId);
                        that.globalData.token = res.data.data.token;
                        wx.getStorage({
                            key: "token",
                            success: function (res) {
                                console.info("缓存中的token=" + JSON.stringify(res))
                            }
                        });
                        wx.getStorage({
                            key: "userId",
                            success: function (res) {
                                // {"errMsg":"getStorage:ok","data":379125443346825200}
                                console.info("缓存中的userId=" + JSON.stringify(res))
                            }
                        })
                    }
                })
            }
        })
    },

    globalData: {
        userInfo: null,
        capsule: null,
        system: null,
        navBarHeight: 0,
        windowWidth: 0,
        windowHeight: 0,
        statusBarHeight: 0,
        token: null, //保存token，token能在多个页面中访问
        // ipStr: '82.156.153.225:8081',
        ipStr: '172.16.21.202:8081',
        // ipStr: '192.168.1.111:8081',

        innerPaddingRight: '',
        innerPaddingLeft: '',
        leftWidth: '',
        // 胶囊信息
        // jnHeight: 0,
        // jnTop: 0,

        // 获取导航栏信息
        // 导航栏的高度 = 状态栏高度 + 胶囊高度 +（胶囊top - 状态栏高度）* 2 
        dhlTop: 0,
        dhlHeight: 0,
        // 状态栏信息
        ztHeight: 0,
        // 导航栏高 + 状态栏高 = 整个 nav的高度
        // nav内容view 的 top 是 导航栏的top ,高度是 导航栏的height 
    }
})
